package com.gxa.web.controller;

import com.alibaba.fastjson.JSONObject;
import com.gxa.common.R;
import com.gxa.service.UserSerice;
import com.gxa.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//登录功能：控制器层
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.验证验证码是否正确
        //获取登录页面输入框的输入验证码
        String vercode = request.getParameter("vercode");
        //获取Session中生成的验证码
        String serverCode = request.getSession().getAttribute("serverCode").toString();
        //创建响应对象
        R r = new R();
        //比较
        if(!serverCode.equalsIgnoreCase(vercode)){//验证码错误
            r.setCode(401);
            r.setMsg("验证码错误");
        }else{//验证码正确
            //2、获取用户名和密码，到数据库查询是否存在
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            //调用service
            UserSerice userSerice = new UserServiceImpl();
            r = userSerice.login(username, password);
        }
        //4.响应数据R
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(JSONObject.toJSONString(r));
    }
}
